import pandas as pd

import requests


def get_pledge_summary_data(stock_code: str):
    response = requests.get("https://datacenter-web.eastmoney.com/api/data/v1/get", params={
        "reportName": "RPT_CSDC_LIST",
        "columns": "ALL",
        "sortColumns": "TRADE_DATE",
        "filter": '(TRADE_DATE>\'2019-05-11\')(SECURITY_CODE="%s")' % stock_code,
    }).json()

    data = response["result"]["data"]

    columns = [
        "TRADE_DATE",
        "PLEDGE_RATIO",
        "PLEDGE_DEAL_NUM",
        "PLEDGE_MARKET_CAP",
        "REPURCHASE_LIMITED_BALANCE",
        "REPURCHASE_UNLIMITED_BALANCE"
    ]
    df = pd.DataFrame(data, columns=columns)
    df = df.sort_values(by=["TRADE_DATE"], ascending=False)
    df = df.rename(columns=dict(zip(columns, [
        "质押日期",
        "质押比例（%）",
        "质押笔数",
        "质押市值（万元）",
        "限售股质押股数（万）",
        "非限售股质押股数（万）",
    ])))

    return df


def get_pledge_detail_data(stock_code: str):
    response = requests.get("https://datacenter-web.eastmoney.com/api/data/v1/get", params={
        "reportName": "RPTA_APP_ACCUMDETAILS",
        "columns": "ALL",
        "sortColumns": "PF_START_DATE",
        "filter": '(TRADE_DATE>\'2019-05-11\')(SECURITY_CODE="%s")' % stock_code,
    }).json()

    data = response["result"]["data"]

    columns = [
        "PF_START_DATE",
        "IS_CONTROL_SHAREHOLDER",
        "MARKET_CAP",
        "PF_NUM",
        "PF_HOLD_RATIO",
        "PF_TSR",
        "WARNING_STATE",
    ]
    df = pd.DataFrame(data, columns=columns)
    df = df.sort_values(by=["PF_START_DATE"], ascending=False)
    df["MARKET_CAP"] = df["MARKET_CAP"].apply(lambda x: x / 1e4)
    df["PF_NUM"] = df["PF_NUM"].apply(lambda x: x / 1e4)
    df = df.rename(columns=dict(zip(columns, [
        "质押日期",
        "是否为控股股东",
        "质押市值（万元）",
        "质押股数（万）",
        "占所持股份比例（%）",
        "占所总股本比例（%）",
        "质押状态",
    ])))

    return df


if __name__ == "__main__":
    # print(get_pledge_summary_data("603656"))
    print(get_pledge_detail_data("000001"))
